package com.djk;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    WordDao wordDao;
    FloatingActionButton fab;//浮动按钮
    EditText etSearch;//搜索框
    ListView listView;//列表视图
    ImageButton ibDelete;//删除按钮
    Spinner spMenu;//下拉框（选择菜单）
    boolean isInitialSelection = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = findViewById(R.id.list_view);

        wordDao = new WordDao(MainActivity.this);
        List<Word> wordList = wordDao.getAllWords();
        //创建适配器
        ArrayAdapter<Word> adapter = new WordAdapter(MainActivity.this, wordList);
        //将数据绑定到适配器
        listView.setAdapter(adapter);

        fab = findViewById(R.id.btn_fab);
        //绑定一个单击后，进行添加操作的事件
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹出添加单词的对话框
                showAddWordDialog();
            }
        });

        //搜索框
        etSearch = findViewById(R.id.ipt_search);
        //编辑框在输入完后，点击搜索后，执行一个事件
        //监听键盘输入
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //输入输入完，点击搜索后的操作
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //获取输入框的值传给下一个页面
                    String serachWord = etSearch.getText().toString();
                    //进行搜索操作
                    searchWord(serachWord);
                    return true;
                }
                return false;
            }
        });

        //处理下拉框
        spMenu = findViewById(R.id.sp_menu);
        // 添加下拉菜单的选项
        String[] menuItems = getResources().getStringArray(R.array.menu_list);
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, menuItems);
        spMenu.setAdapter(spinnerAdapter);


        // 处理下拉菜单选中事件
        spMenu.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 获取选中项的内容
                String selectedItem = parent.getItemAtPosition(position).toString();
                // 添加对 isInitialSelection 的检查和设置
                if (isInitialSelection) {
                    isInitialSelection = false; // 设置为 false，避免初始化时触发操作指南
                    return;
                }
                // 根据选中的内容执行相应操作
                if (selectedItem.equals("关于软件")) {
                    showAboutDialog();
                } else if (selectedItem.equals("操作指南")) {
                    // 将对话框显示操作移到这里
                    String[] operateList = getResources().getStringArray(R.array.operate_list);
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("操作指南")
                            .setItems(operateList, null) // 设置数组信息
                            .show(); // 显示对话框
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 未选择任何内容时的处理
            }
        });

    }

    // 显示关于软件的对话框
    private void showAboutDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        String aboutMessage = getResources().getString(R.string.aboutMsg);
        builder.setTitle("关于软件");
        builder.setMessage(aboutMessage);
        builder.setPositiveButton("确定", null);
        builder.show();
    }

    //处理搜索操作，把数据传给新的页面
    private void searchWord(String serachWord) {
        Intent intent = new Intent(MainActivity.this, SearchResultActivity.class);
        intent.putExtra("searchWord", serachWord);
        startActivity(intent);
    }

    //进行添加的对话框操作
    private void showAddWordDialog() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
        //创建一个自定义对话框视图对象
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_word, null);
        dialogBuilder.setView(dialogView);

        EditText txtWord = dialogView.findViewById(R.id.txt_word);
        EditText txtMeaning = dialogView.findViewById(R.id.txt_meaning);
        dialogBuilder.setTitle("添加单词")
                .setPositiveButton("添加", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //获取输入框的内容
                        String word = txtWord.getText().toString();
                        String meaning = txtMeaning.getText().toString();
                        //添加到数据库中
                        add(word, meaning);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                });
        AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.show();
    }

    //添加单词到数据库
    private void add(String word, String meaning) {
        // 检查数据库中是否已经存在相同单词
        boolean wordExists = wordDao.checkWordExists(word);
        if (wordExists) {
            // 如果单词已经存在，显示提示信息
            Toast.makeText(MainActivity.this, "该单词已存在", Toast.LENGTH_SHORT).show();
        } else {
            // 如果单词不存在，进行添加操作
            long l = wordDao.addWord(new Word(0, word, meaning));
            if (l > 0) {
                Toast.makeText(MainActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                updateListView();
            }
        }
    }


    //更新视图，保证在每次操作后列表实时更新
    private void updateListView() {
        //获取最新的列表数据
        List<Word> newWordList = wordDao.getAllWords();
        ArrayAdapter<Word> adapter = (ArrayAdapter<Word>) listView.getAdapter();
        //清除适配器的原有数据
        adapter.clear();
        adapter.addAll(newWordList);
        adapter.notifyDataSetChanged();
    }

}